<template>
  <el-card class="container">
    <div slot="header" class="clearfix">
      <span>实时预览</span>
      <!--            <el-button style="float: right; padding: 3px 0" type="text" @click="test">点我测试后端</el-button>-->
    </div>
    <div>

      <el-select v-model="viewMethod" placeholder="请选择" @change="viewMethodChange">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <el-row>
      <el-col :span="24">
        <el-row>
          <!--          <el-image width="800" height="500" :src="imageSrc" />-->
          <el-col :style="image_style" :span="24" type="flex" align="middle">
            <!--            <canvas id="canvas" :height="screenHeight" width="100%" @click="toggleFullScreen"/>-->
            <img id="cameraStream" src="" alt="无视频输入" :height="screenHeight" @click="toggleFullScreen">

          </el-col>
          <!--          <el-col :style="image_style" :span="12">-->

          <!--            <img :src="url" alt="无视频输入"  :height="screenHeight" width="100%">-->

          <!--          </el-col>-->

        </el-row>
        <!--        <el-row class="btn">-->
        <!--          <el-button v-if="isPause" class="play" icon="el-icon-video-play" type="primary" circle @click="play" />-->
        <!--          <el-button v-if="!isPause" class="pause" icon="el-icon-video-pause" type="primary" circle @click="pause" />-->
        <!--          &lt;!&ndash;          <el-button class="fullScreen" icon="el-icon-full-screen" type="primary" circle @click="fullScreen" />&ndash;&gt;-->
        <!--        </el-row>-->

      </el-col>
      <!--      <el-col :span="12">-->
      <!--        <el-row>-->
      <!--          <el-col :style="image_style">-->
      <!--            &lt;!&ndash;          <canvas ref="videoCanvas" style="width: 100%;height: 100%;"/>&ndash;&gt;-->
      <!--            <el-table ref="labels" :data="label_dicts" border style="width: 100%" stripe tooltip-effect="dark">-->
      <!--              <el-table-column-->
      <!--                label="标签"-->
      <!--              >-->
      <!--                <template v-slot="scope">-->
      <!--                  {{ scope.row.label }}-->
      <!--                </template>-->
      <!--              </el-table-column>-->
      <!--              <el-table-column-->
      <!--                label="图像"-->
      <!--              >-->
      <!--                <template v-slot="scope">-->
      <!--                  <img alt="" :src="image_src+scope.row.crop" :width="imageWidth" :height="imageHeight">-->
      <!--                </template>-->

      <!--              </el-table-column>-->
      <!--            </el-table>-->
      <!--          </el-col>-->
      <!--        </el-row>-->
      <!--      </el-col>-->
    </el-row>
    <!--    <el-row>-->
    <!--      <el-button v-if="isPause" type="primary" circle @click="play">开始检测</el-button>-->
    <!--      <el-button v-if="!isPause" type="primary" circle @click="pause">结束检测</el-button>-->

    <!--    </el-row>-->
  </el-card>
</template>

<script>
import { Message } from 'element-ui'

export default {
  name: 'RealTimeVideo',
  data() {
    return {

      // 图像数据的 Base64 字符串
      imageSrc: '',
      // WebSocket 对象
      socket: null,
      isPause: true,
      label_dicts: [],
      image_src: 'data:image/jpeg;base64,',
      screenWidth: (5 / 7) * window.innerWidth,
      screenHeight: (5 / 7) * window.innerHeight,
      imageWidth: this.screenWidth / 4,
      imageHeight: this.screenHeight / 5,
      image_style: 'height:' + this.screenWidth + 'px;',
      options: [{ label: '上视角', value: 0 }, { label: '下视角', value: 1 }, { label: '双视角', value: 2 }],
      viewMethod: 2,
      detected_Status: false,
      // image: new Image(),
      currentBlobUrl: null
      // url: '/realTimeVideo/videoStream?viewMethod='+this.viewMethod,

    }
  },
  created() {

    // this.url = '/realTimeVideo/videoStream?viewMethod='+this.viewMethod

  },
  mounted() {
    this.image_src = 'data:image/jpeg;base64,'
    this.screenWidth = (5 / 7) * window.innerWidth
    this.screenHeight = (5 / 7) * window.innerHeight
    this.imageWidth = this.screenWidth / 6
    this.imageHeight = this.screenHeight / 5
    this.image_style = 'height:' + this.screenHeight + 'px'

    this.getConfig()
    this.timer = null
  },
  beforeDestroy() {
    clearInterval(this.timer)
    if (this.currentBlobUrl) {
      URL.revokeObjectURL(this.currentBlobUrl)
    }
    // // 在组件销毁前关闭websocket连接
    // if (this.socket) {
    //   this.socket.close()
    // }
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    getConfig() {
      this.$store.dispatch('systemconfig/getConfig')
        .then(response => {
          if (response.status === 200) {
            this.detected_Status = (response.data.detected_status === 0)
            this.input_view = response.data.input_view

            if (this.detected_Status) {
              this.setInterval2()
            } else {
              if (this.timer != null) {
                clearInterval(this.timer)
                this.timer = null
              }
            }
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
          }
        })
        .catch(error => {
          console.error('获取配置信息失败:', error)
        })
    },
    setInterval() {
      // 出现内存溢出，暂时停用
      // const cameraImage = document.getElementById('cameraStream')
      const maxWidth = 1000 // 最大宽度
      const maxHeight = this.screenHeight// 最大高度（如果需要的话）
      const cameraUrl = '/realTimeVideo/videoStream' // 后端接口URL
      const interval = 50 // 轮询间隔，假设和后端帧率一致
      const camera_canvas = document.getElementById('canvas')
      const ctx2 = camera_canvas.getContext('2d')
      let image = new Image()
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      let fetchAbortController = null // 用于取消fetch请求
      console.log('viewmode is:', 3)
      this.timer = setInterval(() => {
        if (fetchAbortController) {
          fetchAbortController.abort() // 取消前一个fetch请求
        }
        console.log('viewmode is:', 4)
        fetchAbortController = new AbortController() // 创建新的AbortController
        fetch(cameraUrl, { signal: fetchAbortController.signal })
          .then(response => response.blob())
          .then(blob => {
            URL.revokeObjectURL(image.src)
            image = new Image()
            // console.log("viewMethod",this.viewMethod)
            const viewMethod = this.viewMethod
            // cameraImage.src = URL.createObjectURL(blob)
            image.src = URL.createObjectURL(blob)
            image.onload = function() {
              let ratio = Math.min(maxWidth / image.width, maxHeight / image.height)
              console.log('viewmode is:', 5)
              if (viewMethod === 2) {
                const width = image.width * ratio
                const height = image.height * ratio
                image.width = width
                image.height = height
                camera_canvas.width = width
                camera_canvas.height = height
                ctx2.drawImage(image, 0, 0, image.width, image.height)
                return
              }

              canvas.width = image.width
              canvas.height = image.height
              let sy = 0
              let rate = 1
              if (viewMethod === 0) {
                sy = 0
                rate = 2
              } else if (viewMethod === 1) {
                sy = image.height / 2
                rate = 2
              }
              ctx.drawImage(image, 0, 0)
              ratio = Math.min(maxWidth / image.width, maxHeight / image.height * rate)
              const width = image.width * ratio
              const height = image.height * ratio
              // console.log(sy,rate)
              const image_data = ctx.getImageData(0, sy, image.width, image.height / rate)

              camera_canvas.width = width
              camera_canvas.height = height
              ctx2.putImageData(image_data, 0, 0)
            }
          })
          .catch(error => {
            console.error('Error fetching camera stream:', error)
          })
      }, interval)
    },

    setInterval2() {
      const image = document.getElementById('cameraStream')

      const cameraUrl = '/realTimeVideo/videoStream' // 后端接口URL
      const interval = 50 // 轮询间隔，假设和后端帧率一致
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      // const camera_canvas = document.getElementById('canvas')
      // const ctx = camera_canvas.getContext('2d')
      // let image = new Image()
      // let fetchAbortController = null // 用于取消fetch请求
      this.timer = setInterval(() => {
        // if (fetchAbortController) {
        //   fetchAbortController.abort() // 取消前一个fetch请求
        // }
        // fetchAbortController = new AbortController() // 创建新的AbortController
        const viewMethod = this.viewMethod
        // console.log("viewMethod:",viewMethod)
        fetch(cameraUrl + '?viewMethod=' + viewMethod)
          .then(response => response.blob())
          .then(blob => {
            // URL.revokeObjectURL(image.src)
            // console.log("viewMethod",this.viewMethod)

            // if (currentViewMethod !== viewMethod) {
            // // 如果 viewMethod 发生变化，清空图像，避免闪烁
            //   image.src = '';
            //   currentViewMethod = viewMethod;
            //   return;
            // }

            if (this.currentBlobUrl) {
              URL.revokeObjectURL(this.currentBlobUrl)
            }
            this.currentBlobUrl = URL.createObjectURL(blob)
            // image.src = this.currentBlobUrl

            // 处理裁剪逻辑
            // console.log("viewmode is:",6)
            const videoImage = new Image()
            videoImage.src = this.currentBlobUrl
            videoImage.onload = () => {
              canvas.width = videoImage.width
              canvas.height = videoImage.height
              // console.log("width is:",videoImage.width)
              // console.log("height is:",videoImage.height)
              ctx.drawImage(videoImage, 0, 0)

              let cropHeight = videoImage.height
              let startY = 0

              if (this.viewMethod === 0) {
                // 裁剪上半部分
                cropHeight = videoImage.height / 2
              } else if (this.viewMethod === 1) {
                // 裁剪下半部分
                cropHeight = videoImage.height / 2
                startY = videoImage.height / 2
              }

              // console.log("cropHeight is:",cropHeight)
              // console.log("startY is:",startY)

              // 在 canvas 上裁剪图像
              const croppedImageData = ctx.getImageData(0, startY, videoImage.width, cropHeight)
              canvas.height = cropHeight
              ctx.putImageData(croppedImageData, 0, 0)

              // 更新显示的裁剪图像
              image.src = canvas.toDataURL('image/jpeg')
            }
          })
          .catch(error => {
            console.error('Error fetching camera stream:', error)
          })
      }, interval)
    },
    toggleFullScreen() {
      const canvas = document.getElementById('cameraStream')
      if (!document.fullscreenElement) {
        if (canvas.requestFullscreen) {
          canvas.requestFullscreen()
        } else if (canvas.mozRequestFullScreen) { // Firefox
          canvas.mozRequestFullScreen()
        } else if (canvas.webkitRequestFullscreen) { // Chrome, Safari and Opera
          canvas.webkitRequestFullscreen()
        } else if (canvas.msRequestFullscreen) { // IE/Edge
          canvas.msRequestFullscreen()
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.mozCancelFullScreen) { // Firefox
          document.mozCancelFullScreen()
        } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
          document.webkitExitFullscreen()
        } else if (document.msExitFullscreen) { // IE/Edge
          document.msExitFullscreen()
        }
      }
    },

    viewMethodChange() {
      // console.log("viewMethodChange")
      // if(this.timer!=null){
      //   console.log(this.timer)
      //   clearInterval(this.timer)
      //   this.setInterval()
      // }
      // console.log("视角切换:", this.viewMethod);
      // this.setInterval2(); // 切换视角时重新启动视频轮询
    }

    // play() {
    //   this.initWebSocket()
    //   console.log('1111111111111')
    //   // this.imageSrc = 'http://127.0.0.1:8000/hello/'
    //   // 开始检测
    //   startInspec()
    //     .then(response => {
    //       // 开始检测成功传个 1 就行了
    //       console.log(response.data)
    //       if (response.data === 1) {
    //         this.isPause = false
    //         console.log(this.isPause)
    //       }
    //     })
    //     .catch(error => {
    //       console.error('开始检测失败:', error)
    //     })
    // },
    // pause() {
    //   this.socket.close()
    //   stopInspec()
    //     .then(response => {
    //       // 停止检测成功传个 1 就行了
    //       if (response.data === 1) {
    //         this.isPause = true
    //       }
    //     })
    //     .catch(error => {
    //       console.error('停止失败:', error)
    //     })
    // },
    // // todo
    // fullScreen() {
    //
    // },
    // initWebSocket() {
    //   // 创建websocket连接
    //   this.socket = new WebSocket('ws://127.0.0.1:8000/ws/video/')
    //   // 监听websocket事件
    //   this.socket.onopen = (event) => {
    //     console.log('WebSocket连接已打开')
    //   }
    //
    //   this.socket.onmessage = (event) => {
    //     // 接收到消息时的处理
    //     const response = JSON.parse(event.data)
    //     const imageData = response['result_img']// 从事件中获取图像数据
    //     this.label_dicts = response['label_dicts']
    //     console.log(response)
    //     // 在前端中显示图像数据
    //     // this.imageSrc =  URL.createObjectURL(imageData)
    //     // console.log(this.imageSrc)
    //
    //     this.imageSrc = 'data:image/jpeg;base64,' + imageData
    //
    //     // let blob = this.dataURItoBlob('data:image/jpeg;base64,' + imageData)
    //     //
    //     // this.imageSrc = URL.createObjectURL(blob)
    //     // let img = new Image();
    //
    //     // 设置 img 的 width 和 height 属性
    //     //         img.width = 500;
    //     //         img.height = 500;
    //     //         img.src = URL.createObjectURL(blob)
    //     //         let canvas = this.$refs.videoCanvas
    //     //         let ctx = canvas.getContext('2d')
    //     //         ctx.drawImage(img, 0, 0, img.width, img.height);
    //   }
    //
    //   this.socket.onclose = (event) => {
    //     this.isPause = true
    //     console.log('WebSocket连接已关闭')
    //   }
    // },
    // dataURItoBlob(base64Data) {
    //   // console.log(base64Data);//data:image/png;base64,
    //   var byteString
    //   // eslint-disable-next-line brace-style
    //   if (base64Data.split(',')[0].indexOf('base64') >= 0) { byteString = atob(base64Data.split(',')[1]) }// base64 解码
    //   else {
    //     byteString = unescape(base64Data.split(',')[1])
    //   }
    //   var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0]// mime类型 -- image/png
    //
    //   // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    //   // var ia = new Uint8Array(arrayBuffer);//创建视图
    //   var ia = new Uint8Array(byteString.length)// 创建视图
    //   for (var i = 0; i < byteString.length; i++) {
    //     ia[i] = byteString.charCodeAt(i)
    //   }
    //   var blob = new Blob([ia], {
    //     type: mimeString
    //   })
    //   return blob
    // },
    // viewMethodChange(){
    //   console.log('viewMethodChange')
    //   this.url = 'http://127.0.0.1:8000/realTimeVideo/videoStream?viewMethod='+this.viewMethod
    // }

  }

}
</script>

<style lang="scss" scoped>
.container{
  margin: 20px;

  .video{
    display: flex;
    justify-content: center;
    background-color: #262424;

    .el-image{
      width: 60vw;
    }
  }
  .btn{
    display: flex;
    justify-content: space-between;
    background-color: #f5f5f5;

    .el-button{
      background-color: rgb(48,65,86);
      //icon颜色
      color: #F5F7F8;
      //不需要边框
      border:none;
    }

    .el-button:hover{
      color: #45474B;
      background-color: #a6d3ff;
    }
  }
}
</style>
